﻿using UnityEngine;
using System.Collections.Generic;
using System;

public class JsonHelper
{
    public static List<T> JsonToArray<T>(string json)
    {
        string newJson = "{ \"array\": " + json + "}";
        WrapperArray<T> wrapper = JsonUtility.FromJson<WrapperArray<T>>(newJson);
        return wrapper.array;
    }

    public static Dictionary<K, V> JsonToDic<K, V>(string json)
    {
        string newJson = "{ \"dic\": " + json + "}";
        WrapperDic<K, V> wrapper = JsonUtility.FromJson<WrapperDic<K, V>>(newJson);
        return wrapper.ToDic();
    }

    public static string ArrayToJson<T>(List<T> array)
    {
        WrapperArray<T> wrapper = new WrapperArray<T>();
        wrapper.array = array;

        string result = JsonUtility.ToJson(wrapper);
        return result.Remove(0, 9).TrimEnd('}');
    }

    public static string DicToJson<K, V>(Dictionary<K, V> dic)
    {
        WrapperDic<K, V> wrapper = new WrapperDic<K, V>(dic);

        string result = JsonUtility.ToJson(wrapper);
        return result;
    }

    [Serializable]
    private class WrapperArray<T>
    {
        public List<T> array;
    }

    [Serializable]
    private class WrapperDic<K, V> : ISerializationCallbackReceiver
    {
        [SerializeField]
        List<K> keys;
        [SerializeField]
        List<V> values;

        Dictionary<K, V> dic;
        public Dictionary<K, V> ToDic()
        {
            return dic;
        }
        public WrapperDic(Dictionary<K, V> target)
        {
            dic = target;
        }

        public void OnAfterDeserialize()
        {
            var count = Math.Min(keys.Count, values.Count);
            dic = new Dictionary<K, V>(count);
            for (var i = 0; i < count; ++i)
            {
                dic.Add(keys[i], values[i]);
            }
        }

        public void OnBeforeSerialize()
        {
            keys = new List<K>(dic.Keys);
            values = new List<V>(dic.Values);
        }
    }
}
